//从数据库的表中读取数据，		
                //   （1）在内存新建一个链表
                //   （2）查看链表内容

 #include <string.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <mysql/mysql.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
 #include <fcntl.h>
 #include <dirent.h>


 typedef struct  student {
  int code;
  char name[10];
  int age;
  struct student *next;
}STU;

void display(STU *head);
void save(STU *head);
STU *sql_num1(void);


int main(){
    STU*head=NULL;
    head =  sql_num1();
    save(head);
    display(head);
   
   }     

// 将链表内容保存到数据表中
void save(STU *head){
    char sql[100] = {0};
    MYSQL *res = NULL;
    MYSQL *con = NULL;
    con = mysql_init(NULL);
    res = mysql_real_connect(con,"localhost","root","","student",0,NULL,0);
    
    if(res == NULL){
        printf("%s\n",mysql_error(con));
        exit(-1);
    }

    int ret = 0;
    printf("%p\n",head);
    
    STU *p = head->next;
    printf("%p\n",p);
    while(p != NULL) {
        printf("111\n");
        sprintf(sql,"insert into student values(%d,'%s',%d)",p->code,p->name,p->age);
        ret = mysql_query(con,sql);

        if(ret != 0) {
            printf("%s\n",mysql_error(con));
            exit(-1);
        }
        p = p->next;
    }
    mysql_close(con);
}
// 拉sql数据在内存新建一个链表
 STU *sql_num1(void){
    char sql[100] = {"select * from student"};
    MYSQL *res = NULL,*con = NULL;
    int ret = 0;

    con = mysql_init(NULL);
    res = mysql_real_connect(con,"localhost","root","","student",0,NULL,0);
    
    if(res == NULL)
    {
        printf("%s\n",mysql_error(con));
        exit(-1);
    }

    ret = mysql_query(con,sql);
    if(ret != 0)
    {
        printf("%s\n",mysql_error(con));
        mysql_close(con);
        exit(-1);
    }

    MYSQL_RES *res1 = NULL; 
    MYSQL_ROW row = NULL; 
    res1 = mysql_store_result(con); // 把数据取下来
    
    if(res1 == NULL)
    {
        printf("%s\n",mysql_error(con));
        mysql_close(con);
        exit(-1);
    }

    STU *head = NULL;
    head = (STU*)malloc(sizeof(STU));
    memset(head,0,sizeof(STU));
    STU *p = head;

    row = mysql_fetch_row(res1); //获取sql数据
    while(row != NULL) {
        STU *point = malloc(sizeof(STU));
        memset(point,0,sizeof(STU));

        sscanf(row[0],"%d",&point->code);
        sscanf(row[1],"%s",point->name);
        sscanf(row[2],"%d",&point->age);
        printf("2222\n");

        row = mysql_fetch_row(res1);
        p->next = point;
        point->next = NULL;
        p = point;

    }
    mysql_free_result(res1);//释放链接

    mysql_close(con);

    return head;
}

// 查看链表内容
void display(STU *head){
    if(head == NULL) {
        return;
        }
       
        STU *p = head->next;
        while(p != NULL) {
            // 输出code
            printf("id:%d\n",p->code);
            // 输出name
            printf("name:%s\n",p->name);
            // 输出age
            printf("age:%d\n",p->age);
            p = p->next;
        }
}

